package com.koo.modules.bja.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.koo.common.utils.MyStrUtil;
import com.koo.common.utils.PageUtils;
import com.koo.common.utils.Query;
import com.koo.framework.query.MyBatisPlusUtil;
import com.koo.modules.bja.dao.BjaInspectionOrderDao;
import com.koo.modules.bja.entity.BjaInspectionOrderDetailEntity;
import com.koo.modules.bja.entity.BjaInspectionOrderEntity;
import com.koo.modules.bja.service.BjaInspectionOrderDetailService;
import com.koo.modules.bja.service.BjaInspectionOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class BjaInspectionOrderServiceImpl extends ServiceImpl<BjaInspectionOrderDao, BjaInspectionOrderEntity> implements BjaInspectionOrderService {

    @Autowired
    private BjaInspectionOrderDetailService bjaInspectionOrderDetailService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        Object key = params.get("key");
        LambdaQueryWrapper<BjaInspectionOrderEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(MyStrUtil.isNotEmpty(key), BjaInspectionOrderEntity::getInspectionId, key)
                .or().eq(MyStrUtil.isNotEmpty(key), BjaInspectionOrderEntity::getInspectionOrderNo, key);

        IPage<BjaInspectionOrderEntity> page = this.page(
                new Query<BjaInspectionOrderEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<BjaInspectionOrderEntity> listInspectionOrders(Integer maxNum) {
        return baseMapper.listInspectionOrders(maxNum);
    }

    @Override
    public boolean findHasOrderByHeadNo(String headQuarterAllotNo) {
        Integer count = baseMapper.selectCount(MyBatisPlusUtil.createEQWrapper(new Object[]{headQuarterAllotNo}, "headQuarterAllotNo"));
        return MyStrUtil.isNotEmpty(count) && count != 0;
    }

    @Override
    @Transactional
    public void insertByListAndUpdateState(List<BjaInspectionOrderEntity> outOrders, List<BjaInspectionOrderDetailEntity> orderDetails) {
        // 添加主单
        this.saveBatch(outOrders);
        // 批量添加明细
        bjaInspectionOrderDetailService.saveBatch(orderDetails);
        // 更新状态
        outOrders.forEach(item -> {
            item.setStatus(1);
        });
        this.updateBatchById(outOrders);
    }

}